package online.inote.mapper.core;

import lombok.NoArgsConstructor;
import online.inote.mapper.utils.ClassUtils;
import org.springframework.asm.ClassWriter;
import org.springframework.asm.Opcodes;

@NoArgsConstructor(access = lombok.AccessLevel.PRIVATE)
class MapperGenerator extends Generator implements Opcodes {

	private static MapperGenerator generator;
	
    static MapperGenerator getInstance() {
    	if (generator == null) {
    		generator = new MapperGenerator();
    	} 
    	
        return generator;
    }

    Class<?> build(Class<?> signature, Class<?> superClass) {
        ClassWriter cw = new ClassWriter(0);
        String className = getClassName(signature);

        System.out.println(getSignature(signature, superClass));

        cw.visit(V1_8, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, getPath(className),
                getSignature(signature, superClass),
                ClassUtils.getClassPath(Object.class), new String[]{"online/inote/mapper/base/BaseMapper"});

        cw.visitEnd();

        // 获取生成的class文件对应的二进制流
        byte[] code = cw.toByteArray();

        final Class<?> clazz = defineClass(className, code, 0, code.length);

        Thread.currentThread().setContextClassLoader(generator);

        return clazz;
    }

    @Override
    public Type getType() {
        return Type.MAPPER;
    }
}
